#include "audioin.h"
#include "../common/streamer.h"
#include "client.h"
#include "../common/handler.h"

audioIn::audioIn(QObject *parent)
    :QObject (parent)
{
    input_stream = nullptr;
    input_Device = QAudioDeviceInfo::defaultInputDevice();

    settings.setCodec("audio/pcm");
    settings.setSampleRate(44100);
    settings.setSampleType(QAudioFormat::SampleType(1));
    settings.setSampleSize(16);
    settings.setChannelCount(1);
    settings.setByteOrder(QAudioFormat::LittleEndian);

    if(!input_Device.isFormatSupported(settings))
        input_Device.nearestFormat(settings);

    audioInput = new QAudioInput(input_Device,settings,this);
    audioInput->setBufferSize(4000);
}

audioIn::~audioIn()
{
    delete audioInput;
    delete input_stream;
}


void audioIn::record_start()
{
    qDebug()<<"start recording...";
    input_stream = audioInput->start();

    connect(input_stream,&QIODevice::readyRead,
                [=](){
    //当有音频输入时,输入流读取进行录音,然后写给网络输送
        auto data = input_stream->readAll();
        SingleTon<Client>::getReference().write(
           Streamer::pack(Handler::audioTrans,data));
    });
}

void audioIn::record_stop()
{
    audioInput->stop();
    //input_stream = nullptr;
}
